<template>
  <div class="amap-page-container">
    <el-amap class="amap-area"/>
    <div></div>
  </div>
</template>

<style>
  .amap-area {

  }
</style>

<script>
  import {lazyAMapApiLoaderInstance} from 'vue-amap';
  import axios from 'axios';

  var coordtransform = require('coordtransform');

  export default {
    data() {
      return {
        lont: 0,/*经度*/
        lat: 0,/*纬度*/
        zoom: 14,
        center: [0, 0],
        markers: [{position: [0, 0]}],
      };
    },

    methods: {
      onComplete(gps_data) {
        let trans = this.wgs84togcj02(gps_data.position.lng, gps_data.position.lat);
        this.lont = trans[0].toFixed(6);
        this.lat = trans[1].toFixed(6);

        this.getAddr();
      },

      wgs84togcj02(lnt, lat) {
        /*国际转国内*/
        return coordtransform.wgs84togcj02(lnt, lat);
      },

      getAddr: function () {
        let _this = this;
        axios.get('https://restapi.amap.com/v3/geocode/regeo', {
          params: {
            key: 'c128401fbd292e57bfd7398d7a67fa0c',
            location: _this.lont + ',' + _this.lat,

          }
        }).then(function (success_data) {
          let district = success_data.data.regeocode.addressComponent.district;
          let neighborhood = success_data.data.regeocode.addressComponent.neighborhood.name;
          _this.$emit('addr_callback', district+neighborhood);
        })
          .catch(function (error_data) {
            console.log('定位失败');
            _this.$emit('addr_callback', '定位失败');
          });
      }
    },

    mounted: function () {
      let self = this;
      let map;
      lazyAMapApiLoaderInstance.load().then(() => {
        map = new AMap.Map('amap-main', {center: new AMap.LngLat(0, 0)});
        map.plugin('AMap.Geolocation', function () {
          let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition: 'RB'
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, 'complete', self.onComplete);//返回定位信息
        });
      });
    },
  };
</script>
